#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
#include <errno.h> // 用于处理错误码
#include "record.h"

// 获取设备
snd_pcm_t *record_start(const char *name,
                        snd_pcm_format_t format,
                        unsigned int channel,
                        unsigned int rate,
                        snd_pcm_uframes_t *period)
{
    snd_pcm_t *capture;          // PCM设备句柄
    snd_pcm_hw_params_t *params; // PCM硬件参数
    int err;                     // 用于存储错误码
    int dir;

    // 打开PCM设备用于录音（捕捉）
    if ((err = snd_pcm_open(&capture, name, SND_PCM_STREAM_CAPTURE, 0)) < 0)
    {
        fprintf(stderr, "Error opening PCM device %s: %s\n", name, snd_strerror(err));
        return NULL;
    }

    // 分配参数对象，并用默认值填充
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(capture, params);

    // 设置参数
    // 设置访问类型：交错模式
    if ((err = snd_pcm_hw_params_set_access(capture, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
    {
        fprintf(stderr, "Error setting access: %s\n", snd_strerror(err));
        snd_pcm_close(capture);
        return NULL;
    }
    // 设置数据格式：16位小端
    if ((err = snd_pcm_hw_params_set_format(capture, params, format)) < 0)
    {
        fprintf(stderr, "Error setting format: %s\n", snd_strerror(err));
        snd_pcm_close(capture);
        return NULL;
    }
    // 设置声道数：立体声
    if ((err = snd_pcm_hw_params_set_channels(capture, params, channel)) < 0)
    {
        fprintf(stderr, "Error setting channels: %s\n", snd_strerror(err));
        snd_pcm_close(capture);
        return NULL;
    }
    // 设置采样率
    if ((err = snd_pcm_hw_params_set_rate_near(capture, params, &rate, &dir)) < 0)
    {
        fprintf(stderr, "Error setting rate: %s\n", snd_strerror(err));
        snd_pcm_close(capture);
        return NULL;
    }
    printf("sample rate: %d Hz\n", rate);

    // 设置硬件参数
    if ((err = snd_pcm_hw_params(capture, params)) < 0)
    {
        fprintf(stderr, "Error setting HW params: %s\n", snd_strerror(err));
        snd_pcm_close(capture);
        return NULL;
    }

    // 获取周期大小
    snd_pcm_hw_params_get_period_size(params, period, &dir);
    printf("period: %d frames\n", *period);

    return capture;
}

// 关闭设备
void record_stop(snd_pcm_t *capture)
{
    snd_pcm_drain(capture); // 排空PCM设备
    snd_pcm_close(capture); // 关闭PCM设备
}

// 开始录音
snd_pcm_t *start_recording(char **buffer, FILE *pcm_file, snd_pcm_uframes_t *period)
 {
     snd_pcm_t *capture;
     capture = record_start("hw:0,1", SND_PCM_FORMAT_S16_LE, 2, 44100, period);
     if (!capture)
     {
         fprintf(stderr, "Failed to start recording\n");
         return NULL;
     }

     *buffer = (char *)malloc(snd_pcm_frames_to_bytes(capture, *period));
     if (!*buffer)
     {
         perror("malloc");
         record_stop(capture);
         capture = NULL;
         return NULL;
     }

     pcm_file = fopen("output.pcm", "wb");
     if (!pcm_file)
     {
         perror("Error opening output file");
         free(*buffer);
         record_stop(capture);
         capture = NULL;
         return NULL;
     }

     printf("Recording started\n");
     return capture;
 }

 // 停止录音
 void stop_recording(snd_pcm_t *capture, char *buffer, FILE *pcm_file)
 {
     if (capture)
     {
         free(buffer);
         buffer = NULL;

         fclose(pcm_file);
         pcm_file = NULL;

         record_stop(capture);
         capture = NULL;

         printf("Recording stopped\n");
     }
 }


int main()
{
     snd_pcm_t *capture;       // PCM设备句柄
     snd_pcm_uframes_t period; // 每个周期的帧数
     char *buffer;             // 缓冲区，用于存储采集到的音频数据
     FILE *pcm_file;           // 输出PCM文件
     int err;                  // 用于存储错误码

     capture = record_start("hw:0,1", SND_PCM_FORMAT_S16_LE, 2, 44100, &period);
     if (!capture)
     {
         return 1;
     }

     printf("period: %d frames\n", period);

     buffer = (char *)malloc(snd_pcm_frames_to_bytes(capture, period)); // 分配缓冲区
     if (!buffer)
     {
         perror("malloc");
         record_stop(capture);
         return 1;
     }

     // 打开输出文件
     pcm_file = fopen("output.pcm", "wb");
     if (!pcm_file)
     {
         perror("Error opening output file");
         free(buffer);         // 释放缓冲区
         record_stop(capture); // 关闭PCM设备
         return 1;
    }

     // 录制数据
     printf("Recording... Press Ctrl+C to stop.\n");
     while (1)
     {
         snd_pcm_sframes_t frames = snd_pcm_readi(capture, buffer, period); // 从PCM设备读取数据
         if (frames < 0)
         {
             fprintf(stderr, "Error from read: %s\n", snd_strerror(frames));
             if (frames == -EPIPE)
             {
                 snd_pcm_prepare(capture);
             }
         }

         fwrite(buffer, snd_pcm_frames_to_bytes(capture, frames), 1, pcm_file); // 将读取的数据写入文件
}

     // 清理资源
     free(buffer);     // 释放缓冲区
     fclose(pcm_file); // 关闭文件
     record_stop(capture);

     printf("Recording complete.\n");

   return 0;
}